Getting the Picture I

In this recipe we cache images to cut down on load times.






Discussion

Quiz time: what does the following fragment of HTML do?
<IMG SRC="" HEIGHT=34 WIDTH=34>
Your first response is probably that this isn't legal, but it is. The browser reserves a 34x34 block of space for an image, but doesn't load anything into the space. The HTML in this recipe does this 16 times to create space for the grid above. Then we use JavaScript to "fill in the blanks."

The two bitmaps are loaded through the use of Image objects in JavaScript:


var alien;
var eye;

function Setup()
{
	var j = 1;
	// Create the images
	alien = new Image();
	eye   = new Image();
	// Load graphics into the images
	alien.src = "../GRAFX/MOUSEOVR/ALIEN.GIF"
	eye.src   = "../GRAFX/MOUSEOVR/EYE.GIF";
	// Assign images to the HTML array of images.
	for(var i = 1; i < document.images.length; i++) {
		if((j % 2) == 0)
			document.images[i].src = alien.src;
		else
			document.images[i].src = eye.src;
		j++;			
		if((j % 5) == 0) 
			j++;
	}
}
It's important to notice that you must specify the src attribute when loading images this way; document.images[3]="myBitmap.jpg" is not legal and will generate an error.

The browser only loads two images to create the grid, and that can be important when you need to duplicate a graphic many times across a page. Inserting <IMG SRC="myBitmap.jpg"> into the HTML source over and over will cause the browser to load multiple copies of the image--which slows down page loading. By inserting "empty" images, then filling them with JavaScript-cached copies, you can speed up page display and cut down on network traffic at the same time.

Copyright ©1998 by Charles River Media, All Rights Reserved